import axios from "axios";
import router from "../router";

const http = axios.create({
    baseURL: import.meta.env.APP_BASE_URL, // url = base url + request url
});

http.interceptors.request.use(
  function (config) {
    if(localStorage.token){
      config.headers.Authorization = 'Bearer '+localStorage.token ;
    }
    // console.log(localStorage.token);
    return config;
  },
  function (error) {
    //对请求错误做些什么
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  function (response) {
    //2xx范围内的状态码都会触发该函数，
    //对响应数据做点什么，比如，将session存储下来
    return response;
  },
  function (error) {
    //超出2xx 范围的状态码都会触发该函数。
    //对响应错误做点什么
    const {status} = error.response;
    if(status === 401){
      console.log('授权失败');
      localStorage.removeItem('token');
      router.push('/login');
    }
    return Promise.reject(error);
  }
);

export default http;